package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;



    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */

    @GetMapping("/page")
    public R<Page> pageQuery(int page, int pageSize, String name) {
        //创建Setmeal分页构造器
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        //构造查询构造器
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        lambdaQueryWrapper.like(name != null, Setmeal::getName, name);
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, lambdaQueryWrapper);
        //创建DishDto分页构造器
        Page<DishDto> dishDtoPage = new Page<>();
        //拷贝数据
        BeanUtils.copyProperties(setmealPage, dishDtoPage, "records");
        //获取setmealPage中records的数据
        List<Setmeal> records = setmealPage.getRecords();
        List<DishDto> list = records.stream().map(item -> {
            //创建DishDto对象
            DishDto dishDto = new DishDto();
            //拷贝数据
            BeanUtils.copyProperties(item, dishDto);
            //获取Setmeal中categoryID,通过id获取categoryName
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 添加操作
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("获取到的数据:{}", setmealDto);
        setmealService.saveWithSetmealDishs(setmealDto);
        return R.success("添加成功!");
    }

    /**
     * 删除操作
     *
     * @param ids
     * @return
     */

    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("获取到的id:{}", ids);
        setmealService.deleteWithSetmealDishs(ids);
        return R.success("删除成功!");
    }

    /**
     * 编辑页面回显数据
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @Cacheable(value = "setmealCache", key = "#id", unless = "#result==null")
    public R<SetmealDto> get(@PathVariable Long id) {
        log.info("获取到的id:{}", id);
        SetmealDto setmealDto = setmealService.getWithId(id);
        return R.success(setmealDto);
    }

    /**
     * 更新数据
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        log.info("获取到的数据:{}", setmealDto);
        setmealService.updateWithSetmealDish(setmealDto);
        return R.success("更新数据");
    }

    /**
     * 批量起售停售
     *
     * @param stat
     * @param ids
     * @return
     */
    @PostMapping("/status/{stat}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> updateStatus(@PathVariable int stat, @RequestParam List<Long> ids) {
        log.info("获取到的id:{}", ids);
        log.info("获取到的status:{}", stat);
        List<Setmeal> setmeals = setmealService.listByIds(ids);
        setmeals = setmeals.stream().map(item -> {
            item.setStatus(stat);
            return item;
        }).collect(Collectors.toList());
        setmealService.updateBatchById(setmeals);
        return R.success("更新成功");
    }


    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //构造条件查询,已知catoryId查询套餐表
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus, 1);
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);
        return R.success(setmealList);
    }
}
